<!DOCTYPE html>
<html lang="zh">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>10绘制矩形</title>
    <link rel="stylesheet" href="./utils/reset.css" />
    <script src="./utils/webgl-helper.js"></script>
  </head>
  <body>
    <canvas id="canvas"></canvas>

    <script type="shader-source" id="vertexShader">
      precision mediump float;
      attribute vec2 rect_Position;
      attribute vec2 canvas_Size;
      attribute vec4 rect_Point_Color;
      varying vec4 v_Color;

      void main(){
        vec2 position = (rect_Position / canvas_Size) * 2.0 - 1.0;
        position = position * vec2(1.0, -1.0);
        gl_Position = vec4(position, 0.0, 1.0);
        v_Color = rect_Point_Color;
      }
    </script>
    <script type="shader-source" id="fragmentShader">
      precision mediump float;
      varying vec4 v_Color;

      void main(){
        vec4 color = v_Color / vec4(255,255,255,1);
        gl_FragColor = color;
      }
    </script>
    <script>
      const canvas = getCanvas("#canvas");
      resizeCanvas(canvas);

      const gl = getContext(canvas);
      const program = createSimpleProgramFromScript(
        gl,
        "vertexShader",
        "fragmentShader"
      );
      gl.useProgram(program);

      const canvas_Size = gl.getAttribLocation(program, "canvas_Size");
      gl.vertexAttrib2f(canvas_Size, canvas.width, canvas.height);

      const position = [
        30, 30, 255, 0, 0, 1, 30, 300, 0, 255, 0, 1, 300, 300, 0, 255, 0, 1,
        300, 30, 0, 0, 255, 1,
      ];

      const rect_Position = gl.getAttribLocation(program, "rect_Position");
      const rect_Point_Color = gl.getAttribLocation(
        program,
        "rect_Point_Color"
      );

      gl.enableVertexAttribArray(rect_Position);
      gl.enableVertexAttribArray(rect_Point_Color);

      const buffer = gl.createBuffer();
      gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
      gl.vertexAttribPointer(rect_Position, 2, gl.FLOAT, false, 24, 0);
      gl.vertexAttribPointer(rect_Point_Color, 4, gl.FLOAT, false, 24, 0);
      gl.bufferData(
        gl.ARRAY_BUFFER,
        new Float32Array(position),
        gl.STATIC_DRAW
      );

      const indices = [0, 1, 2, 0, 2, 3];
      const indicesBuffer = gl.createBuffer();
      gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, indicesBuffer);
      gl.bufferData(
        gl.ELEMENT_ARRAY_BUFFER,
        new Uint16Array(indices),
        gl.STATIC_DRAW
      );

      gl.clearColor(0, 0, 0, 1);

      function render(gl) {
        gl.clear(gl.COLOR_BUFFER_BIT);
        gl.drawElements(gl.TRIANGLES, indices.length, gl.UNSIGNED_SHORT, 0);
      }

      render(gl);
    </script>
  </body>
</html>
